﻿using Entity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ProdService;
using UI.Filters;
using ViewModels.Career;
using ViewModels.JsonResult;
using ViewModels.Pwd;
using ViewModels.Shared;
using ViewModels.User;
using static Global.Const;

namespace UI.ApiControllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PwdController : BaseController
    {
        public PwdController(UserService userService, PhoneService phoneService)
            : base(userService, phoneService)
        {
        }

        [HttpPost]
        [Route(nameof(Forget))]
        public WithError Forget([FromForm]ResetModel model)
        {
            WithError result = checkCaptcha(model.Captcha);
            if (result.Errors.Count > 0)
            {
                return result;
            }

            result = checkSMS(model);
            if (result.Errors.Count > 0)
            {
                return result;
            }

            userService.ResetPwd(model);

            result.Succeed = true;
            return result;
        }

        [HttpPost]
		[Route(nameof(Edit))]
		public RegisterResult Edit([FromForm]_ChangePwdModel model)
        {
            RegisterResult result = new();

            if (!userService.IsPasswordCorrect(model.OldPassword))
            {
                result.Errors.Add(nameof(model.OldPassword), "* 旧密码错误");
                return result;
            }
            else if (model.OldPassword == model.Password)
            {
                result.Errors.Add(nameof(model.Password), "* 密码不能与旧密码相同");
                return result;
            }
            else
            {
                userService.SetPwd(model.Password);
                Response.Cookies.Delete(CookieName.UserId);
                Response.Cookies.Delete(CookieName.Password);
            }
            result.Succeed = true;
            return result;
        }


    }
}
